//
//  LoginViewController.m
//  ZBarScan
//
//  Created by QF_iOS on 2017/5/24.
//  Copyright © 2017年 QF_iOS. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIView *bigBgVView;
@property (nonatomic, strong) UITextField *usernameTextField;
@property (nonatomic, strong) TTPasswordView *passwordTextField;
@property (nonatomic, strong) JQIndicatorView *indicator;
@property (nonatomic, strong) UILabel *loadLb;
@property (nonatomic, strong) UIView *loadV;
@property (nonatomic, assign) BOOL keyBoardOK;
@end

@implementation LoginViewController


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.usernameTextField becomeFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"登录";
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 16, 40, 40)];
    [backBtn setImage:[UIImage imageNamed:@"back_arrow"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
    self.navigationItem.leftBarButtonItem = item;
    
    self.usernameTextField.delegate = self;
    [self createHeaderView];

    [self createLoginUserNameAndPassWord];
    [self createIndicatorView];
    // Do any additional setup after loading the view.
}
- (void)backBtnAction {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)createHeaderView {

    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,  416 / 2 )];
    bgView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:bgView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 416 / 2)];
    imageView.backgroundColor = [UIColor grayColor];
    imageView.image = [UIImage imageNamed:@"login_image"];
    [bgView addSubview:imageView];
 
    
    //监听键盘是否呼出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upViews:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardOK) name:UIKeyboardDidShowNotification object:nil];
    
    //添加手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    
    
}

#pragma mark - 键盘弹出时界面上移及还原
-(void)upViews:(NSNotification *) notification{
    
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int keyBoardHeight = keyboardRect.size.height;
    
    //使视图上移
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y = -keyBoardHeight + 150;
    self.view.frame = viewFrame;
    _keyBoardOK = NO;
}

- (BOOL)keyBoardOK
{
    _keyBoardOK = YES;
    return YES;
}

-(void)tapAction{


    if ([self.passwordTextField.textField isFirstResponder]&&_keyBoardOK)

    {
        
        [self.passwordTextField.textField resignFirstResponder];
        
        //使视图还原
        CGRect viewFrame = self.view.frame;
        viewFrame.origin.y = 0;
        self.view.frame = viewFrame;
        
        
    }
    if ([self.usernameTextField isFirstResponder]&&_keyBoardOK)
    {
        
        [self.usernameTextField resignFirstResponder];
        
        //使视图还原
        CGRect viewFrame = self.view.frame;
        viewFrame.origin.y = 0;
        self.view.frame = viewFrame;
        
        
    }

}


#pragma mark -- 创建用户名输入框、密码、和登录
- (void)createLoginUserNameAndPassWord {
    
//    UILabel *usernameLabel = [UILabel createLabelFrame:CGRectMake(120 / 2, 575 / 2, 85 / 2, 30) title:@"" titleColor:[UIColor blackColor] titleFont:15 bgColor:[UIColor whiteColor] radius:0 inSuperView:self.view isSizeToFit:YES];
    
    UILabel *usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(120 / 2, 701 / 2 - 100, 60, 30)];
    usernameLabel.text = @"用户名";
    usernameLabel.textColor  = [UIColor blackColor];
    usernameLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:usernameLabel];
    
    UILabel *passwordLable = [[UILabel alloc] initWithFrame:CGRectMake(120 / 2, 802 / 2  - 100, 60, 30)];
    passwordLable.text = @"密    码";
    passwordLable.textColor  = [UIColor blackColor];
    passwordLable.backgroundColor = [UIColor clearColor];
    [ self.view addSubview:passwordLable];
    
    //账号输入框
    self.usernameTextField = [[UITextField alloc]initWithFrame:CGRectMake(120 / 2 + 60, 697 / 2  - 100, 200, 36)];
    self.usernameTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.usernameTextField.clearButtonMode = UITextFieldViewModeAlways;
    //取出账号字段
   NSString *loginUserName = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginUserName"];
    if (loginUserName.length != 0) {
        self.usernameTextField.text = loginUserName;
    }
    
    [self.view addSubview:self.usernameTextField];
    
    
    //登录按钮
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake((kScreenWidth - 500/2) / 2 , 975 / 2  - 100, 500 / 2, 100 / 2);
    loginBtn.backgroundColor = kNavigationMainColor;
    [loginBtn setTitle:@"取消" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    loginBtn.layer.masksToBounds  = YES;
    loginBtn.layer.cornerRadius = 4;
    
    [self.view addSubview:loginBtn];
    

    //密码输入框
    

    self.passwordTextField = [[TTPasswordView alloc] initWithFrame:CGRectMake(120 / 2 + 60, 797 / 2  - 100, 200, 36)];
    self.passwordTextField.elementCount = 6;
    self.passwordTextField.elementColor=UIColorFromRGB(0xd5d5d5);
    [self.view addSubview:self.passwordTextField];
    __block LoginViewController *weakself=self;
    self.passwordTextField.passwordBlock = ^(NSString *password) {
        if (password.length==6) {
            //将账号存储到本地
            [[NSUserDefaults standardUserDefaults] setObject:weakself.usernameTextField.text forKey:@"LoginUserName"];
            
            
            CGRect viewFrame = weakself.view.frame;
            viewFrame.origin.y = 0;
            weakself.view.frame = viewFrame;

            NSLog(@"%@",password);
            //自动登录
            if (weakself.usernameTextField.text.length  == 0) {
                
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入账号" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *suerAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertVC addAction:suerAction];
                [weakself presentViewController:alertVC animated:YES completion:^{
                    
                }];
            } else {
                //调用登录接口
                [weakself.indicator startAnimating];
                weakself.loadLb.hidden = NO;
                weakself.loadV.hidden = NO;
                NSLog(@"%@,%@",weakself.usernameTextField.text,weakself.passwordTextField.textField.text);
                [YKNetHelp getDataWithPath:ApiSExternalAPPLoginIn andParams:@{@"Login_Name":weakself.usernameTextField.text,@"User_PW":weakself.passwordTextField.textField.text,@"Entity_Code":@"BXJC"} andComplete:^(BOOL success, id result) {
                    [weakself.indicator stopAnimating];
                    weakself.loadLb.hidden = YES;
                    weakself.loadV.hidden = YES;
                    NSLog(@"%@",result);
                
                    AppDelegate *appdelegate = kAppDelegate;
                    appdelegate.publicProperty.loginModel = [WZLoiginModel mj_objectWithKeyValues:result[@"Data"]];
                    
                    if (result[@"Data"] != NULL) {
                        [weakself.navigationController popViewControllerAnimated:YES];
                    } else {
                        //弹出提示框
                        [weakself showTextHUDWithStr:@"账号或密码错误"];
                    }
                }];
            }
            
            
        }
        
        
    };


    
}

//网络加载指示器
- (void)createIndicatorView
{
    _loadV = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 130, 130)];
    _loadV.backgroundColor = [UIColor blackColor];
    _loadV.center = CGPointMake(self.view.center.x, self.view.center.y + 20);
    _loadV.alpha = 0.5;
    _loadV.layer.cornerRadius = 6;
    _loadV.layer.masksToBounds = YES;
    [self.view addSubview:_loadV];
    
    _loadLb = [UILabel createLabelFrame:CGRectMake(100 , CGRectGetMaxY(_loadV.frame) - 30, 100, 20) title:@"登录中..." titleColor:[UIColor whiteColor] titleFont:17 bgColor:nil radius:0 inSuperView:self.view isSizeToFit:NO];
    _loadLb.textAlignment = NSTextAlignmentCenter;
    _loadLb.center = CGPointMake(self.view.center.x, _loadLb.center.y);
    
    _indicator = [[JQIndicatorView alloc]initWithType:JQIndicatorTypeCyclingCycle tintColor:[UIColor whiteColor]];
    _indicator.center = self.view.center;
    [self.view addSubview:_indicator];
    
    
    _loadLb.hidden = YES;
    _loadV.hidden = YES;
}

- (void)loginAction {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
 

}
//
//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
////    [self.usernameTextField becomeFirstResponder];
//    
////    [UIView animateWithDuration:0.3 animations:^{
////        self.view.frame = CGRectMake(0, -100, kScreenWidth,  100 +kScreenheight);
////    }];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
